﻿using Microsoft.SharePoint;
using Slam.Logging;
using StructureMap;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Slam.StructureMap
{
    public class TypeContainerBuilder : ITypeContainerBuilder
    {   
        public TypeContainerBuilder()
        {
        }

        public ITypeContainer Build(SPContentType contentType)
        {
            return Build(contentType.ParentWeb.Site.Url, new SlamType(contentType));
        }

        public ITypeContainer Build(SPList list)
        {
            return Build(list.ParentWeb.Site.Url, new SlamType(list));
        }

        private ITypeContainer Build(string siteCollectionUrl, SlamType type)
        {
            SlamSettings settings = new SlamSettings(siteCollectionUrl);
            string connectionString = "";
            string errorEmailToAddress = "";
            MessageSeverity severityThreshold = MessageSeverity.Information;
            if (settings.Settings.ContainsKey("slamConnectionString"))
            {
                connectionString = settings.Settings["slamConnectionString"].ToString();
            }
            if (settings.Settings.ContainsKey("slamErrorEmailToAddress"))
            {
                errorEmailToAddress = settings.Settings["slamErrorEmailToAddress"].ToString();
            }
            if (settings.Settings.ContainsKey("slamSeverityThreshold"))
            {
                string messageSeverity = settings.Settings["slamSeverityThreshold"].ToString();
                if (!String.IsNullOrEmpty(messageSeverity))
                    severityThreshold = (MessageSeverity)Enum.Parse(typeof(MessageSeverity), messageSeverity);
            }
            DefaultLogSettings logSettings = new DefaultLogSettings(connectionString, errorEmailToAddress, severityThreshold);
            var container = new Container(c =>
            {
                c.For<DefaultLogSettings>().Use(logSettings);
                c.For<ILog>().Use<DefaultLog>();
                c.For<SlamContext>().Use<SlamContext>();
            });
            return new TypeContainer(container);
        }
    }
}
